package com.tao.base.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Configuration
public class MPConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInnerInterceptor.setMaxLimit(1000L);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        return mybatisPlusInterceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                String  currentUser = getCurrentUser();
                LocalDateTime now = LocalDateTime.now();

                this.strictInsertFill(metaObject, "createDate", LocalDateTime.class, now);
                this.strictInsertFill(metaObject, "changeDate", LocalDateTime.class, now);
                this.strictInsertFill(metaObject, "createPeople", String.class, currentUser);
                this.strictInsertFill(metaObject, "changePeople", String.class, currentUser);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                String currentUser = getCurrentUser();
                LocalDateTime now = LocalDateTime.now();

                this.strictUpdateFill(metaObject, "changeDate", LocalDateTime.class, now);
                this.strictUpdateFill(metaObject, "changePeople", String.class, currentUser);
            }

            private String getCurrentUser() {
                // 如果需要获取Spring容器中的其他Bean，可以注入进来
                // 例如：通过注入SecurityUtils或其他工具类获取当前用户
                return "陶虹润";
            }
        };
    }
}
